<template>
  <div class="main_box">
    <el-row class="header-row">
      <el-col>
        <div class="search_wrap">
          <el-form :inline="true" :model="filters" class="demo-form-inline" ref="searchForm">
            <!--<el-form-item prop="name">
              <el-input v-model="filters.name" clearable placeholder="场所名称"></el-input>
            </el-form-item>-->
            <el-form-item prop="streetIds">
              <Region :streetValues="filters.streetIds" @regionChange="handleItemChange" :isChangeOnSelect="true"> </Region>
            </el-form-item>
            <el-form-item prop="address">
              <el-input v-model="filters.address" placeholder="请输入地址名称"></el-input>
            </el-form-item>
            <el-form-item prop="villageId">
              <el-select placeholder="请选择小区" v-model="filters.villageId" filterable clearable>
                <el-option v-for="item in villageList" :value="item.id" :label="item.name" :key="item.id"></el-option>
              </el-select>
              <!-- <el-input v-model="filters.villageName" placeholder="请输入小区名称"></el-input> -->
            </el-form-item>
            <el-form-item prop="residentAddress">
              <el-cascader placeholder="请选择XX栋XX单元XX层" :options="residentAddressList" @change="" v-model="filters.residentAddress" :props="{ label: 'name', value: 'id', checkStrictly: true }"></el-cascader>
            </el-form-item>
            <el-form-item>
              <el-button icon="el-icon-search" type="primary" @click="onSearch">查询</el-button>
              <el-button icon="el-icon-refresh-left" @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col>
        <div class="opration_wrap">
          <el-tooltip content="刷新" placement="top">
            <el-button circle icon="el-icon-refresh-right" @click="reload" size="mini"></el-button>
          </el-tooltip>
          <!--<el-button type="primary" plain icon="fa fa-plus" v-has="permissionAdd" @click="handleClickAdd()" size="mini"> 新增</el-button>-->
        </div>
      </el-col>
    </el-row>

    <el-row ref="tableRow">
      <!-- 列表 -->
      <el-table :data="dataList" :fit="true" highlight-current-row v-loading="listLoading" element-loading-text="数据加载中，请稍后..." empty-text="对不起，没有找到相关数据！">
        <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
        <el-table-column align="center" label="场所地址">
          <template slot-scope="scope">
            <span>{{ scope.row.provinceName }}{{ scope.row.cityName }}{{ scope.row.areaName }}{{ scope.row.streetName }}{{ scope.row.address }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" width="200" label="小区名称" prop="villageName"> </el-table-column>
        <el-table-column label="栋单元层" align="center" width="200">
          <template slot-scope="scope">
            <div>{{ scope.row.buildName }}{{ scope.row.unitName }}{{ scope.row.floorName }}</div>
          </template>
        </el-table-column>
        <el-table-column label="场所类型" align="center">
          <template slot-scope="scope">
            <span>
              <el-tag size="mini" effect="dark" :type="formatLocaleTypes(scope.row.localeType)">
                {{ formatLocaleType(scope.row.localeType) }}
              </el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" width="200" label="创建人" prop="createUserName"> </el-table-column>
        <el-table-column align="center" width="200" label="创建时间" prop="createDate"> </el-table-column>
        <!--<el-table-column align="center" width="200" label="修改人" prop="modifyUserName">
        </el-table-column>
        <el-table-column align="center" width="200" label="修改时间" prop="modifyDate">
        </el-table-column>-->
        <el-table-column label="操作" width="136" fixed="right">
          <template slot-scope="scope">
            <el-button v-has="permissionSee" @click="handleClickDetail(scope.row)" size="mini">查看</el-button>
            <el-dropdown trigger="click" size="small">
              <el-button type="primary"> <i class="fa fa-list-ul"></i>更多 </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-has="permissionValidateUser" @click.stop.native="handleClickValidate(scope.row)">主用户校验 </el-dropdown-item>
                <el-dropdown-item v-has="permissionExportUser" @click.stop.native="exportUser(scope.row)">导出场所用户 </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页工具条 -->
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNo"
        :page-sizes="[20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, jumper, next, pager, prev"
        :total="page.pageTotal"
      ></el-pagination>
    </el-row>

    <el-dialog center :visible.sync="validateUser.show" title="主用户校验" width="fit-content">
      <div style="text-align: end; margin-bottom: 5px">
        <el-button circle plain type="success" icon="el-icon-plus" @click="add"> </el-button>
      </div>
      <el-table :data="validateUser.list" max-height="600px">
        <el-table-column label="用户名" align="center" width="200">
          <template slot-scope="scope">
            <el-input v-model="scope.row.fullName" clearable></el-input>
          </template>
        </el-table-column>
        <el-table-column label="电话号码" align="center" width="200">
          <template slot-scope="scope">
            <el-input v-model.number="scope.row.phone" clearable></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button circle plain type="danger" icon="el-icon-minus" @click="sub(scope.$index)"> </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer">
        <el-button type="primary" @click="confirmValidate"> 确定 </el-button>
        <el-button @click="validateUser.show = false"> 取消 </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import LocaleApi from '@/api/address/locale';
import Region from '@/components/Region';
import VillageAPi from '@/api/address/village';
import VillageAreaApi from '../../api/address/villageArea';
import fileDownload from 'js-file-download';
export default {
  name: 'LocaleManagement',
  inject: ['reload'], //注入局部刷新
  data() {
    return {
      dataList: [],
      listLoading: true,
      filters: {
        name: '',
        address: '',
        villageName: '',
        streetIds: [],
        residentAddress: [],
        villageId: '',
        provinceId: '',
        cityId: '',
        areaId: '',
        streetId: '',
      },
      page: {
        pageNo: 1,
        pageTotal: 0,
        pageSize: 20,
      },
      villageList: [],
      residentAddressList: [],

      permissionSee: 'SYSTEM_MANAGER_ADDRESS_LOCALE_LIST_SEE',
      permissionValidateUser: 'SYSTEM_MANAGER_ADDRESS_LOCALE_LIST_VALIDATE_USER',
      permissionExportUser: 'SYSTEM_MANAGER_ADDRESS_LOCALE_LIST_EXPORT',
      validateUser: {
        show: false,
        list: [],
      },
      row: '', //点击某一行的数据
    };
  },
  components: {
    Region,
  },
  watch: {
    'filters.streetIds'(val) {
      this.villageId = '';
      this.villageName = '';
      this.villageList = [];
      if (val.length > 0) {
        this.getVillageList();
      }
    },
    'filters.villageId'(val) {
      this.residentAddress = [];
      if (val) this.getResidentAddressList();
    },
  },
  mounted() {
    this.init();
    window.addEventListener('keydown', this.keyDown);
  },
  activated() {
    this.listData();
  },
  destroyed() {
    window.removeEventListener('keydown', this.keyDown, false);
  },
  methods: {
    init() {
      let _this = this;
      _this.listLoading = true;
      _this.listData();
      _this.getTableHeight();
    },
    keyDown(e) {
      //如果是回车则执行查询方法
      if (e.keyCode == 13) {
        this.onSearch();
      }
    },
    getTableHeight() {
      this.$nextTick(function () {
        this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        window.onresize = () => {
          this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        };
      });
    },
    async getVillageList() {
      const { streetIds } = this.filters;
      const params = {
        provinceId: streetIds[0] || '',
        cityId: streetIds[1] || '',
        areaId: streetIds[2] || '',
        streetId: streetIds[3] || '',
      };
      const { data } = await VillageAPi.villageList(params);
      this.villageList = data || {};
    },
    async getResidentAddressList() {
      const { data } = await VillageAreaApi.getListTree({ villageId: this.filters.villageId });
      this.residentAddressList = data || [];
    },
    // handleResidentAddressChange(e){
    //   const {filters} = this
    // },
    add() {
      this.validateUser.list.push({
        fullName: '',
        phone: '',
      });
    },
    sub(index) {
      this.validateUser.list.splice(index, 1);
    },
    formatLocaleType(cellValue) {
      if (cellValue === 1) {
        return '公共';
      } else if (cellValue === 2) {
        return '专属';
      }
    },
    formatLocaleTypes(cellValue) {
      if (cellValue === 2) {
        return 'success';
      } else if (cellValue === 1) {
        return 'danger';
      }
    },
    handleSizeChange(size) {
      let _this = this;
      _this.page.pageSize = size;
      _this.listData();
    },
    handleCurrentChange(val) {
      let _this = this;
      _this.page.pageNo = val;
      _this.listData();
    },
    handleClickValidate(row) {
      const { validateUser } = this;
      this.row = row;
      LocaleApi.listData({ localeId: row.localeId }).then((res) => {
        validateUser.list = res.data;
        validateUser.show = true;
      });
    },
    confirmValidate() {
      const { row, validateUser } = this;
      let list = validateUser.list;
      validateUser.list = list = validateUser.list.filter((item) => {
        return item.fullName || item.phone;
      });

      const reg = /^1(3|4|5|6|7|8|9)\d{9}$/;
      let flag = list.find((item) => {
        if (!item.fullName) {
          this.$message.error('填写用户名');
          return true;
        }
        if (!item.phone) {
          this.$message.error('请填写电话号码');
          return true;
        }
        if (!reg.test(item.phone)) {
          this.$message.error('电话号码格式错误');
          return true;
        }
      });

      if (flag) return;

      this.$confirm('确认提交', '提示', {}).then(() => {
        const params = {
          localeId: row.localeId,
          list: validateUser.list,
        };
        LocaleApi.setLocalRestrict(params).then(() => {
          this.$Utils.notifySuccess();
          validateUser.show = false;
        });
      });
    },
    /*handleClickAdd () {
      let _this = this
      _this.$router.push('/address/villageAdd')
    },
    handleClickEditor (row) {
      let _this = this
      _this.$router.push({
        path: '/address/villageEdit',
        query: { id: row.villageId }
      })
    },*/
    handleClickDetail(row) {
      let _this = this;
      _this.$router.push({
        path: '/address/localeDetail',
        query: { id: row.localeId },
      });
    },
    resetForm() {
      this.$refs.searchForm.resetFields();
      this.filters.provinceId = '';
      this.filters.cityId = '';
      this.filters.areaId = '';
      this.filters.streetId = '';
      this.filters.streetIds = [];
      this.fiilters.residentAddress = [];
      // this.filters.buildId = ""
      // this.filters.floorId = ""
      // this.filters.unitId = ""
      this.onSearch();
    },
    onSearch() {
      this.listLoading = true;
      this.page.pageNo = 1;
      this.listData();
    },
    handleItemChange(val) {
      this.filters.provinceId = val.provinceId;
      this.filters.cityId = val.cityId;
      this.filters.areaId = val.areaId;
      this.filters.streetId = val.streetId;
      if (val.provinceId) {
        this.filters.streetIds = [val.provinceId, val.cityId, val.areaId, val.streetId];
      } else {
        this.filters.streetIds = [];
      }
    },
    listData() {
      // 获取列表数据
      let cond = {
        pageNo: this.page.pageNo,
        pageSize: this.page.pageSize,
      };
      cond.name = this.filters.name;
      cond.provinceId = this.filters.provinceId;
      cond.cityId = this.filters.cityId;
      cond.areaId = this.filters.areaId;
      cond.streetId = this.filters.streetId;
      cond.address = this.filters.address;
      cond.villageName = this.filters.villageName;
      (cond.floorId = this.filters.residentAddress[2] || ''), (cond.unitId = this.filters.residentAddress[1] || ''), (cond.buildId = this.filters.residentAddress[0] || ''), (cond.villageId = this.filters.villageId);
      LocaleApi.listLocale(cond)
        .then((res) => {
          this.dataList = res.data.list;
          this.page.pageTotal = res.data.total;
          this.listLoading = false;
        })
        .catch((err) => {
          this.listLoading = false;
        });
    },
    exportUser(row) {
      this.$confirm('确定导出场所用户？', '提示', {}).then(() => {
        let loading = this.$loading({
          lock: true,
          text: '导出中',
          background: 'rgba(0, 0, 0, 0.7)',
        });
        LocaleApi.exportUser({ localeId: row.localeId })
          .then((res) => {
            fileDownload(res, '场所关联用户表格.xlsx');
          })
          .finally(() => {
            loading.close();
          });
      });
    },
  },
};
</script>
<style lang="scss">
@import '@/assets/css/views/content.scss';
</style>
